const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs'
};

class MountTableMigration {
    constructor() {
        this.connection = null;
    }

    async connect() {
        try {
            this.connection = await mysql.createConnection(dbConfig);
            console.log('🔌 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    async disconnect() {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 创建玩家坐骑表
    async createCharacterMountsTable() {
        try {
            console.log('📋 开始创建玩家坐骑表...');

            const createTableSQL = `
                CREATE TABLE IF NOT EXISTS character_mounts (
                    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '玩家坐骑ID',
                    characterId BIGINT NOT NULL COMMENT '角色ID',
                    mountBaseId INT NOT NULL COMMENT '坐骑基础ID',
                    level INT NOT NULL DEFAULT 1 COMMENT '坐骑等级',
                    experience BIGINT NOT NULL DEFAULT 0 COMMENT '坐骑经验值',
                    transLevel INT NOT NULL DEFAULT 0 COMMENT '转职等级',
                    status TINYINT NOT NULL DEFAULT 0 COMMENT '是否上阵：0-休息，1-休息，2-出战',
                    currentAp INT NOT NULL DEFAULT -1000 COMMENT '当前攻击力',
                    currentHp INT NOT NULL DEFAULT -1000 COMMENT '当前生命值',
                    currentMp INT NOT NULL DEFAULT -1000 COMMENT '当前法力值',
                    currentSp INT NOT NULL DEFAULT -1000 COMMENT '当前速度',
                    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
                    updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
                    INDEX idx_characterId (characterId),
                    INDEX idx_mountBaseId (mountBaseId),
                    INDEX idx_status (status),
                    INDEX idx_character_status (characterId, status),
                    CONSTRAINT fk_character_mounts_characterId FOREIGN KEY (characterId) REFERENCES characters (id) ON DELETE CASCADE,
                    CONSTRAINT fk_character_mounts_mountBaseId FOREIGN KEY (mountBaseId) REFERENCES mount_base (id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='玩家坐骑表';
            `;

            await this.connection.execute(createTableSQL);
            console.log('✅ 玩家坐骑表创建成功');
        } catch (error) {
            console.error('❌ 创建玩家坐骑表失败:', error.message);
            throw error;
        }
    }

    // 创建坐骑训练次数表
    async createMountTrainingTable() {
        try {
            console.log('📋 开始创建坐骑训练次数表...');

            const createTableSQL = `
                CREATE TABLE IF NOT EXISTS mount_training (
                    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '训练记录ID',
                    characterId BIGINT NOT NULL COMMENT '角色ID',
                    characterMountId INT NOT NULL COMMENT '玩家坐骑ID',
                    trainingDate DATE NOT NULL COMMENT '训练日期',
                    dailyCount INT NOT NULL DEFAULT 0 COMMENT '当日训练次数',
                    totalExperience BIGINT NOT NULL DEFAULT 0 COMMENT '累计获得经验',
                    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
                    updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
                    INDEX idx_characterId (characterId),
                    INDEX idx_characterMountId (characterMountId),
                    INDEX idx_trainingDate (trainingDate),
                    UNIQUE INDEX idx_character_mount_date (characterId, characterMountId, trainingDate),
                    CONSTRAINT fk_mount_training_characterId FOREIGN KEY (characterId) REFERENCES characters (id) ON DELETE CASCADE,
                    CONSTRAINT fk_mount_training_characterMountId FOREIGN KEY (characterMountId) REFERENCES character_mounts (id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='坐骑训练次数表';
            `;

            await this.connection.execute(createTableSQL);
            console.log('✅ 坐骑训练次数表创建成功');
        } catch (error) {
            console.error('❌ 创建坐骑训练次数表失败:', error.message);
            throw error;
        }
    }

    // 执行完整的迁移
    async runMigration() {
        try {
            await this.connect();

            console.log('🚀 开始执行坐骑系统数据库迁移...');

            // 创建玩家坐骑表
            await this.createCharacterMountsTable();

            // 创建坐骑训练次数表
            await this.createMountTrainingTable();

            console.log('🎉 坐骑系统数据库迁移完成！');

        } catch (error) {
            console.error('❌ 迁移失败:', error.message);
            throw error;
        } finally {
            await this.disconnect();
        }
    }
}

// 执行迁移
async function main() {
    const migration = new MountTableMigration();
    try {
        await migration.runMigration();
        process.exit(0);
    } catch (error) {
        console.error('迁移执行失败:', error);
        process.exit(1);
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    main();
}

module.exports = MountTableMigration;
